package com.adgroup.doremon_ad;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import util.Config;
import util.Utility;

import model.Comment;
import model.User;
import model.Video;
import adapter.AdapterComment;
import adapter.JsonParse;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.adgroup.doremon_ad.LoginActivity.AsyntaskLoginWithSocial;
import com.adgroup.doremon_ad.MainActivity.AsynGetLinkYouTube;
import com.adgroup.doremon_ad.MainActivity.AsynRemoveVideo;
import com.adgroup.doremon_ad.R;
import com.androidquery.AQuery;
import com.facebook.FacebookException;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Request.GraphUserCallback;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.model.GraphUser;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import database.Database;

public class CommentActivity extends SherlockActivity{

	private ActionBar mActionBar;
	private Facebook facebook;
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.menu_detailchart, menu);
		return super.onCreateOptionsMenu(menu);
		
	}
	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
		switch (item.getItemId()) {
		
		case android.R.id.home:
			Utility.HideKeyboard(getApplicationContext(), etComment);
			finish();
			break;
		case R.id.menuShareFacebook: 			
			User u = new Database(CommentActivity.this).getUser();
			//if(u!=null && u.getType().equalsIgnoreCase(Config.typeFacebook))
			{				
				SharedPreferences share = getSharedPreferences("sharefilmllk",
					      MODE_PRIVATE);
					    SharedPreferences.Editor editor = share.edit();
					   
				//SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(DetailChartActivity.this);
				facebook.setAccessToken(share.getString("access", "0"));
				long expied = share.getLong("access_expires", 0);
				facebook.setAccessExpires(expied);
				 
				if(facebook.getSession()!=null){ 
					AlertDialog.Builder alert = new AlertDialog.Builder(CommentActivity.this);
					alert.setTitle(title1);
					alert.setMessage(getResources().getString(R.string.shareinfordwithfacebook)+" "+share.getString("username", ""));
					alert.setNeutralButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							publishFeedDialog(null);
						}
					});
					alert.setPositiveButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
					alert.setNegativeButton(getResources().getString(R.string.another_account_fb), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							loginFacebook();
						}
					});
					alert.show();	
					
				}
				else{
					loginFacebook();
				}
			}
			/*else{
				loginFacebook();
			} */
			break;
		default:
			break;  
		}
		return super.onOptionsItemSelected(item);
	}

	private ProgressDialog progress;

	@SuppressWarnings("deprecation")
	private void loginFacebook() {
		facebook.authorize(CommentActivity.this,new String[]{"email","publish_stream","offline_access"}, new DialogListener() {
			
			@Override
			public void onFacebookError(FacebookError e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onError(DialogError e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onComplete(Bundle values) {
				Request.executeMeRequestAsync(facebook.getSession(), new GraphUserCallback() {
					
					@SuppressLint("DefaultLocale")
					@Override
					public void onCompleted(GraphUser user, Response response) {
						if (user != null) {
							//progress = ProgressDialog.show(CommentActivity.this, "",
								//	getResources().getString(R.string.logining), true);
							String access = facebook.getSession().getAccessToken();
							Date d = facebook.getSession().getExpirationDate();
							long milliseconds = d.getTime();
							SharedPreferences share = getSharedPreferences(
									"sharefilmllk", MODE_PRIVATE);
							SharedPreferences.Editor editor = share
									.edit();

							editor.putLong("access_expires",
									milliseconds);
							editor.putString("access", access);

							
							String email = (String) user.asMap().get("email");
							String birthday = (String) user.asMap().get("birthday");
							String nickname = (String) user.asMap().get("name");
							String username = (String) user.asMap().get("username");
							editor.putString("username", nickname);
							editor.commit();
							String gender = (String) user.asMap().get("gender");
							if(gender.toLowerCase().equalsIgnoreCase("male")){
								gender = "1";
							}
							else if(gender.toLowerCase().equalsIgnoreCase("female")){
								gender = "0";
							}
							String avatar = (String) user.asMap().get("id");
							avatar = "http://graph.facebook.com/"+avatar+"/picture";
							//String[] params = new String[] {email,username,birthday,nickname,gender,avatar,Config.typeFacebook,"1","gcmid"};//1: facebook
						//	new AsyntaskLoginWithSocial().execute(params);
							publishFeedDialog(null);
						}
					}
				});
			}
			
			@Override
			public void onCancel() {
				
			}
		});
	
	}
	private void publishFeedDialog(Object object) {
		Bundle params = new Bundle();
		String url1 = getResources().getString(R.string.urldownloadapp);
		url1 = url1.replace(" ", "%20");
	    params.putString("name", title1);
	    params.putString("caption", title1); 
	    params.putString("description", description);  
	    params.putString("link", player_default);
	   // params.putString("link", url);
	    Log.d("log",url1);
	    params.putString("picture", imageID); 
	    @SuppressWarnings("deprecation")
		WebDialog feedDialog = (
	        new WebDialog.FeedDialogBuilder(CommentActivity.this,
	        		facebook.getSession(),
	            params))
	        .setOnCompleteListener(new OnCompleteListener() {

	            @Override
	            public void onComplete(Bundle values,
	                FacebookException error) {
	                if (error == null) {
	                    // When the story is posted, echo the success
	                    // and the post Id.
	                    final String postId = values.getString("post_id");
	                    if (postId != null) {
	                        Toast.makeText(CommentActivity.this,
	                        		title1 +" is shared",
	                            Toast.LENGTH_SHORT).show();
	                    }
	                    
	                }	                
	            }

	        })
	        .build();
	    feedDialog.show();
	}
	ImageView ivVide;
	Button btnComment;
	ListView lvComment;
	ProgressBar waitingComment;
	EditText etComment;
	TextView tvTitle;
	AdapterComment adapter;
	private View footerLoadMore;
	User u;
	int page = 1;
	String videoID;
	String comment;
	Video v;
	LinearLayout root;
	String imageID;
	String title,title1;
	String description;
	Button btnPlayVideo;
	String player_default, player_mobile, ID;
	
	private Handler handler = new Handler();
	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.comment);
		
		 AdView mAdView = (AdView) this.findViewById(R.id.adView);
		    AdRequest adRequest = new AdRequest.Builder().build();
		    mAdView.loadAd(adRequest);
		    
		facebook = new Facebook(getResources().getString(R.string.facebook_app_id));
		
		/*handler.post(new Runnable() {
			
			@Override
			public void run() {
				StartAppAd.init(CommentActivity.this, Config.devIDStartApp, Config.appIDStartApp); 
				StartAppSearch.init(CommentActivity.this, Config.devIDStartApp, Config.appIDStartApp);
				StartAppSearch.showSearchBox(CommentActivity.this); 
			}
		}); */
		
		//action bar
		mActionBar = getSupportActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(false);
		mActionBar.setDisplayUseLogoEnabled(true);
		mActionBar.setHomeButtonEnabled(true);
		mActionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_actionbar));
		
		getControl();
		videoID = getIntent().getStringExtra("videoID");
		imageID = getIntent().getStringExtra("imageID");
		title1 = getIntent().getStringExtra("title");
		title = getIntent().getStringExtra("title");
		ID = getIntent().getStringExtra("ID");
		player_default = getIntent().getStringExtra("player_default");
		player_mobile = getIntent().getStringExtra("player_mobile");
		
		description = getIntent().getStringExtra("desc");

		mActionBar.setTitle(title);
		
		//load image vide;
		try {
			AQuery aq = new AQuery(CommentActivity.this);
			Bitmap placeholder = aq.getCachedImage(R.drawable.imageload);
			aq.id(ivVide).image(imageID, true,
						true, 0, 0, placeholder, AQuery.FADE_IN_NETWORK, 0.5f);
			if(title.length()>=20){
				title = title.substring(0, 20)+"...";
			}
			tvTitle.setText(title);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		eventControl();
	}
	
	private void eventControl() {
		root.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				try {
					imm.hideSoftInputFromWindow(etComment.getWindowToken(), 0);
					
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		});
		btnPlayVideo.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				try {					
					String url = player_mobile;
					if(url.length()<=6){
						url = player_default;
						url = url.substring(url.indexOf("v=")+2, url.lastIndexOf("&feature"));
					}
					else{
						url = url.substring(url.lastIndexOf("v=")+2);
					}
					if(MainActivity.hmUrl.containsKey(url) ){
						Intent intent = new Intent(CommentActivity.this, VideoViewBuffer.class);
						intent.putExtra("ID",  MainActivity.hmUrl.get(url));
						intent.putExtra("videoID",  url);
						intent.putExtra("IDInt",  ID);
						intent.putExtra("title",  title);
						intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
						startActivity(intent);
						overridePendingTransition(R.anim.in, R.anim.out);
					}
					else{
						new AsynGetLinkYouTube().execute(new String[]{url, ID+""});
					}
				
				} catch (Exception e) {
				} 
			}
		});
		btnComment.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				comment = etComment.getText().toString();
				if(comment.equalsIgnoreCase("")){
					new AlertDialog.Builder(CommentActivity.this)
					.setTitle(getResources().getString(R.string.error))
					.setMessage(getResources().getString(R.string.errornullcomment))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etComment, true);
								}
					}).show();
				}
				
				else{
					u = new Database(CommentActivity.this).getUser();
					if(u==null){
						new AlertDialog.Builder(CommentActivity.this)
						.setTitle(getResources().getString(R.string.buttonlogin))
						.setMessage(getResources().getString(R.string.messagelogintocomment))
						.setNegativeButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								Intent i = new Intent(CommentActivity.this, LoginActivity.class);
								startActivityForResult(i, Config.requestCommentToLogin);
							}
						})
						.setPositiveButton(CommentActivity.this.getResources().getString(R.string.cancel),
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
									}
						}).show();
					}
					else{
						new AsynSendComment().execute(new String[]{comment});
					}
				}
			}
		});		
		adapter = new AdapterComment(new ArrayList<Comment>(), CommentActivity.this);
		lvComment.setAdapter(adapter);
		lvComment.setOnScrollListener(new EndlessScrollListenerComment());
		new AsynLoadComment().execute();
	}
	
	class AsynGetLinkYouTube extends AsyncTask<String, Void, String>
	{
		String videoID;
		String ID;
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();			
			progress = ProgressDialog.show(CommentActivity.this, "",
					getResources().getString(R.string.loading), true);	
		}
		@Override
		protected String doInBackground(String... params) {
			this.videoID = params[0];
			this.ID = params[1];
			return JsonParse.getInstance().getVideoLink(getApplicationContext(), params[0]);
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			progress.dismiss();
			try {
				JSONObject json = new JSONObject(result);
					String url = json.getString(Config.result);
					  
					if(url.equalsIgnoreCase("&&signature=")){
						new AsynRemoveVideo().execute(new String[]{this.ID});
						Utility.ShowAlert(CommentActivity.this, getResources().getString(R.string.error), getResources().getString(R.string.error_canot_play));
					}
					else{
						MainActivity.hmUrl.put(this.videoID, url);
						Intent intent = new Intent(CommentActivity.this, VideoViewBuffer.class);
						intent.putExtra("ID",  url);
						intent.putExtra("videoID",  this.videoID);
						intent.putExtra("IDInt",  this.ID);
						intent.putExtra("title",  title);
						intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
						startActivity(intent);
						overridePendingTransition(R.anim.in, R.anim.out);
					}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	class AsynRemoveVideo extends AsyncTask<String, Void, Void>
	{

		@Override
		protected Void doInBackground(String... params) {
			JsonParse.getInstance().removeVideo(getApplicationContext(), params[0]);
			return null;
		}
		
	}
	private void setEditTextFocus(EditText et, boolean isFocused)
	{
		et.setCursorVisible(isFocused);
		et.setFocusable(isFocused);
		et.setFocusableInTouchMode(isFocused);

	    if (isFocused) 
	    {
	    	et.requestFocus();
	    }
	    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
	}
	private void getControl() {
		ivVide = (ImageView) findViewById(R.id.imageViewVideo);
		btnComment = (Button) findViewById(R.id.buttonComment);
		btnPlayVideo = (Button) findViewById(R.id.buttonPlayVideo);
		lvComment = (ListView) findViewById(R.id.listViewComment);
		tvTitle = (TextView) findViewById(R.id.textViewTitleVideoComment);
		etComment = (EditText) findViewById(R.id.editTextComment);
		footerLoadMore = LayoutInflater.from(CommentActivity.this).inflate(R.layout.footervideo, null);
		lvComment.addFooterView(footerLoadMore);
		footerLoadMore.setVisibility(View.INVISIBLE);
		root = (LinearLayout) findViewById(R.id.root_comment);
		waitingComment = (ProgressBar) findViewById(R.id.progressBarWaitingComment);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		facebook.authorizeCallback(requestCode, resultCode, data);
		if(requestCode==Config.requestCommentToLogin && resultCode==RESULT_OK){//register then login
			u = new Database(getApplicationContext()).getUser();
			new AsynSendComment().execute(new String[]{comment});
		}
	}
	//class load more search friend
	public class EndlessScrollListenerComment implements OnScrollListener {

		private int visibleThreshold;
		private int previousTotal;
		private boolean loading;

		public EndlessScrollListenerComment() {
			visibleThreshold = 1;
			previousTotal = 0;
			loading = true;
		}

		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (loading) {
				if (totalItemCount > previousTotal) {
					loading = false;
					previousTotal = totalItemCount;			
				}
			}
			if (!loading
					&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {				
				new AsynLoadComment().execute();
				loading = true;
			}			
		}

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub

		}

	}
	//send comment
	class AsynSendComment extends AsyncTask<String, Void, String>
	{
		ArrayList<Comment> arr = new ArrayList<Comment>();
		private ProgressDialog progress;
		public AsynSendComment(){
			arr.clear();
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress = ProgressDialog.show(CommentActivity.this, "",
					getResources().getString(R.string.alert_sending_comment), true);
		}
		@Override
		protected String doInBackground(String... arg0) {
			return JsonParse.getInstance().sendComment(ID, u.getUserId(), arg0[0]);
		}
		@Override
		protected void onPostExecute(String result) {
			try {
				JSONObject json = new JSONObject(result);
				if(!json.getString(Config.result).equalsIgnoreCase(Config.norow)){
					JSONArray arr = json.getJSONArray(Config.result);
					for(int i=0;i<arr.length();i++){
						JSONObject obj = arr.getJSONObject(i);
						String userid = obj.getString(Comment.KEY_ID);
						String comment = obj.getString(Comment.KEY_COMMENT);
						String nickname = obj.getString(Comment.KEY_NICKNAME);
						String datepublish = obj.getString(Comment.KEY_DATEPUBLISH);
						Comment c = new Comment(userid, comment, datepublish, nickname);
						this.arr.add(c);
					}
					Toast.makeText(CommentActivity.this, getResources().getString(R.string.alert_successful_comment), Toast.LENGTH_LONG).show();
					etComment.setText("");
					Utility.HideKeyboard(CommentActivity.this, etComment);
					adapter.resetChart(this.arr);	
					page = 2;
				}
			} catch (JSONException e) {
				Log.e("error",e.getMessage());
				e.printStackTrace();
			}
			progress.dismiss();
		}
		
	}
	/*private StartAppAd startAppAd = new StartAppAd(this); 
	@Override 
	public void onResume(){ 
	      super.onResume(); 
	      startAppAd.onResume(); 
	  } 
	@Override 
	  public void onPause() { 
	      super.onPause(); 
	      startAppAd.onPause(); 
	  } 
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		if(keyCode==KeyEvent.KEYCODE_HOME){
			 startAppAd.showAd(); 
			    startAppAd.loadAd(); 
		}
		return super.onKeyDown(keyCode, event);
	}*/
	class AsynLoadComment extends AsyncTask<Void, Void, String>
	{
		ArrayList<Comment> arr = new ArrayList<Comment>();
		public AsynLoadComment(){
			arr.clear();
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			if(adapter.getCount()==0){
				waitingComment.setVisibility(View.VISIBLE);
				footerLoadMore.setVisibility(View.INVISIBLE);
			}
			else{
				waitingComment.setVisibility(View.INVISIBLE);
				footerLoadMore.setVisibility(View.VISIBLE);
			}
		}
		@Override
		protected String doInBackground(Void... arg0) {
			return new JsonParse().getComment(ID, page++);		
		}
		@Override
		protected void onPostExecute(String result) {
			try {
				JSONObject json = new JSONObject(result);
				if(!json.getString(Config.result).equalsIgnoreCase(Config.norow)){
					JSONArray arr = json.getJSONArray(Config.result);
					for(int i=0;i<arr.length();i++){
						JSONObject obj = arr.getJSONObject(i);
						String userid = obj.getString(Comment.KEY_ID);
						String comment = obj.getString(Comment.KEY_COMMENT);
						String nickname = obj.getString(Comment.KEY_NICKNAME);
						String datepublish = obj.getString(Comment.KEY_DATEPUBLISH);
						Comment c = new Comment(userid, comment, datepublish, nickname);
						this.arr.add(c);
					}
					adapter.updateChart(this.arr);					
				}
			} catch (JSONException e) {
				Log.e("error",e.getMessage());
				e.printStackTrace();
			}
			waitingComment.setVisibility(View.INVISIBLE);
			footerLoadMore.setVisibility(View.INVISIBLE);
		}
		
	}
}
